package com.waikuai.shop.controller;

import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.dto.UpdatePasswordDTO;
import com.waikuai.shop.dto.UpdatePaymentPasswordDTO;
import com.waikuai.shop.dto.UpdateProfileDTO;
import com.waikuai.shop.service.UserService;
import com.waikuai.shop.vo.EmployeeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 个人信息管理控制器
 * @author waikuai
 */
@Slf4j
@RestController
@RequestMapping("/profile")
@RequiredArgsConstructor
public class ProfileController {

    private final UserService userService;

    /**
     * 获取当前用户信息
     */
    @GetMapping
    public Result<EmployeeVO> getMyProfile() {
        log.info("获取当前用户信息");
        
        try {
            Long userId = getCurrentUserId();
            EmployeeVO profile = userService.getMyProfile(userId);
            return Result.success("查询成功", profile);
        } catch (Exception e) {
            log.error("获取当前用户信息失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新个人信息
     */
    @PutMapping
    public Result<String> updateMyProfile(@Validated @RequestBody UpdateProfileDTO dto) {
        log.info("更新个人信息: {}", dto);
        
        try {
            Long userId = getCurrentUserId();
            userService.updateMyProfile(dto, userId);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新个人信息失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<String> updateMyPassword(@Validated @RequestBody UpdatePasswordDTO dto) {
        log.info("修改密码");
        
        try {
            Long userId = getCurrentUserId();
            userService.updateMyPassword(dto, userId);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 修改支付密码
     */
    @PutMapping("/payment-password")
    public Result<String> updateMyPaymentPassword(@Validated @RequestBody UpdatePaymentPasswordDTO dto) {
        log.info("修改支付密码");
        
        try {
            Long userId = getCurrentUserId();
            userService.updateMyPaymentPassword(dto, userId);
            return Result.success("支付密码修改成功");
        } catch (Exception e) {
            log.error("修改支付密码失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 获取认证主体（UserDetails）
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            String username = userDetails.getUsername();
            
            // 通过用户名查找用户ID
            com.waikuai.shop.entity.User user = userService.findByUsername(username);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            return user.getId();
        } else {
            throw new RuntimeException("无法获取用户信息");
        }
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            Long userId = getCurrentUserId();
            String avatarUrl = userService.uploadAvatar(file, userId);
            log.info("头像上传成功，用户ID: {}, 头像URL: {}", userId, avatarUrl);
            return Result.success(avatarUrl);
        } catch (Exception e) {
            log.error("头像上传失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
}
